<?php
// | Author: Hei Dousha
// +----------------------------------------------------------------------
// | date: 2015-1-15

namespace Common\Controller;
class BaseController extends CommonController{
	protected $model,$data;
	
	protected function _initialize(){
		parent::_initialize();
    }

    /**
     * 是否登录
     * @return bool
     */
	public function is_login(){
        $aid = getAdminId();
        if(!$aid){
            //用户是否存在
            $map['a.pk_id'] = $aid;
            $map['a.status'] = 0;
            $map['_string'] = 'a.fk_role_id = r.pk_id';
            $field = 'a.pk_id,a.password,a.encrypt,a.fk_role_id,a.nickname,r.name AS role_name,r.menu_auth,r.access_auth';
            $info = M()->table('sys_admin a,sys_role r')->where($map)->field($field)->find();
            if (empty($info)){
                if(IS_AJAX){
                    $this->rtnResult(99,'请先登录');
                }else{
                    //验证访问合法性
                    if (empty($_COOKIE[md5('xxy_allow_login')]) && BIND_MODULE != 'Admin') die('Illegal operation');
                    header('location:'.C('APP_URL').'/Admin/Public/login');
                }
                return false;
            }
            createAdminToken($info);
        }
        return true;
	}


    /**
     * 获取分页数据列表
     * @param $modelName 模型名称
     * @param $condition 条件
     * @param string $field 字段
     * @param string $order 排序
     * @param string $group 分组
     * @return array
     */
    protected function getRows($modelName,$condition,$field = '',$order='',$group='',$having=''){
        if(is_array($modelName)){
            $model = M()->table($modelName);
            foreach($modelName as $key => $val){
                $condition[$val.'.status'] = 0;
            }
            $order = $order ? $order : reset($modelName).".pk_id desc"; //排序默认按主表的pk_id降序
        }else{
            $condition['status'] = 0;
            $model = $modelName ? M($modelName) : $this->model;
            $order = $order ? $order : "pk_id desc";
        }

        //创建分页数据
        $page = I('page');
        $page_num = I('rows');
        if($page && $page_num){
            $data['page'] = $page;
            $data['page_num'] = $page_num;
            $model->page($page,$page_num);
        }
        $rows = $model->where($condition)->field($field)->order($order)->group($group)->having($having)->select();
        $rows = empty($rows) ? array() : $rows;
        if($page && $page_num){
            //多表查询时特殊处理
            if(is_array($modelName)){
                $model = M()->table($modelName);
            }
            $data['count'] = $model->where($condition)->count();
            $data['rows'] = $rows;
        }else{
            $data = $rows;
        }
        return $data;
    }

	
    /**
     * 获取单条数据详情
     * @param object $model 实例化的模型
     * @param array $conditions 条件
     * @param string|array $field 字段
     * @param string $order 按字段排序
     * @return array
     */
	protected function getDataInfo($model,$conditions,$field='',$order = ''){
		$conditions['status'] = 0;
		$info = $model->where($conditions)->field($field)->order($order)->find();
		return $info ? $info : array();
	}

    /**
     * 创建条件
     * @param $map 当前条件
     */
    protected function create_condition(&$map,$table=''){
        //计算主表名称
        if(is_array($table)){
            foreach($table as $val){
                $tb_name = $val; //j.name
                break;
            }
        }else{
            $tb_name = $table;
        }

        //按名称
        $name = I('name');
        $name && $map["$tb_name.name"] = array('like',"%$name%");
    }


    /**
     * 数据过滤
     * @param $modelName 模型名称
     * @param $condition 当前条件
     */
    protected function dataFilter($modelName,&$condition){
        if(empty($this->adminInfo['fk_role_id'])){
           $this->is_login(1);
        }
        if($this->adminInfo['fk_role_id'] != 1){
            $hid = $this->adminInfo['data_auth'];
            empty($hid) && $hid = 0;
            $hidArr = explode(',',$hid);
            $modelName = str_change_x($modelName);
            if(in_array($modelName,array('hospital','nurse','patient'))){
                if($condition['pk_id'] && in_array($condition['pk_id'],$hidArr)) return;
                $condition['pk_id'] = array('IN',$hidArr);
            }elseif(in_array($modelName,array('business_single','charge_log','attendance_log','director_log','director_bus_log','',''))){
                $dubid =  M('department_sub')->where("fk_hpl_id IN ($hid)")->getField('pk_id',true);
                if(!empty($condition['fk_dub_id'])){
                    if(is_array($condition['fk_dub_id'])){
                        $condition['fk_dub_id'][1] = array_intersect($condition['fk_dub_id'][1],$dubid);
                        return;
                    }else{
                        if($condition['fk_dub_id'] && in_array($condition['fk_dub_id'],$dubid)) return;
                    }
                }
                $condition['fk_dub_id'] = empty($dubid) ? array('eq',-1) : array('IN',$dubid);
            }elseif(in_array($modelName,array('department','department_sub','check_dpt_record','check_nursing_fee','check_all_fee','single_record','single'))){
                if($condition['fk_hpl_id'] && in_array($condition['fk_hpl_id'],$hidArr)) return;
                $condition['fk_hpl_id'] = array('IN',$hidArr);
            }
        }
    }


    /**
     * 记录操作
     * @param $title 操作名
     * @param string $content 详细内容
     */
    protected function create_log($title,$content=''){
        if($title){
            //获取角色名
            $adminInfo = getAdminInfo();
            $data['fk_adm_id'] = $adminInfo['pk_id'];
            $data['fk_role_name'] = $adminInfo['role_name'];
            $data['fk_adm_name'] = $adminInfo['nickname'];
            $data['title'] = $title;
            $data['ip'] = get_client_ip();
            $data['content'] = $content;
            $OpreatLog = M('OpreatLog');
            $this->addData($OpreatLog,'','',$data);
        }
    }

    /**
     * 显示视图
     * @param string $data 数据
     * @param string $file 视图文件
     */
	protected function showView($data='',$file=''){
        if(MODULE_NAME == 'System' || MODULE_NAME == 'Admin'){
            //管理员信息
            $data['adminInfo'] = $adminInfo = getAdminInfo();

            //获取执行操作
            if(ACTION_NAME != 'edit' || CONTROLLER_NAME != 'Menu'){
                if ($adminInfo['fk_role_id'] != 1){
                    $map['pk_id'] = array('in',explode(',', $adminInfo['access_auth']));
                }
                $menuId = M('SysMenu')->where("control = '%s'",MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME)->getField('pk_id');
                $map['status'] = 0;
                $map['fk_menu_id'] = $menuId;
                $data['access'] = M('SysAccess')->where($map)->getField('access',true);
            }
        }

		//模板输出
		if (!empty($data) && is_array($data)){
			foreach ($data as $key => $value){
				$this->assign($key,$value);
			}
		}
		$this->display($file);
	}

    /**
     * 检查身份合法性
     * @param string $action_type 节点类型 1为免检节点
     * @return bool
     */
	protected function checkAuth($action_type=''){
		//验证登陆
		$this->is_login();

		//验证权限
        $adminInfo = getAdminInfo();

        //获取当前菜单信息
        $menuInfo = M('SysMenu')->where("control = '%s'",MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME)->find();
		if ($adminInfo['fk_role_id'] != 1){
			//检查访问权限
			if (!in_array($menuInfo['pk_id'], explode(',', $adminInfo['menu_auth']))){
				$this->error('没有访问权限');
			}

			//检查操作权限
			if (ACTION_NAME != 'index'){
				//获取该操作ID
				$acessId = M('access')->where('fk_menu_id = %d AND access = "%s"',$menuInfo['pk_id'],ACTION_NAME)->getField('pk_id');
				if (!in_array($acessId, explode(',', $adminInfo['access_auth'])) && !$action_type){
					$this->error('没有操作权限');
				}	
			}	
		}
        return $adminInfo;
	}


	/**
	 * 添加数据
	 * Enter description here ...
	 * @param unknown_type $model 模型
	 * @param int|string $error 错误信息, 默认空返回结果 ， 为字符串时"成功时输出|失败时"，按结果输出
	 * @param int|string $url 成功后跳转地址, 默认空 , 为字符串时 "[模块/][控制器/]操作|[模块/][控制器/]操作",按结果跳转
	 * @param array $data 要添加的数据
	 * @param unknown_type $startTuarn 是否事务
	 */
	protected function addData($model='',$error='',$url='',$data = '',$startTuarn = ''){
		//分解返回信息,$error[0]成功时返回,$error[1]失败时返回
        if(!is_numeric($error)){
            $error && $error = explode('|', $error);
        }

		//赋值模型
		$model = empty($model) ? $this->model : $model;
		
		//创建数据
		!$model->create($data) && $this->error($model->getError(),$url[1]);

		//添加数据
		$id = $model->add();
		if (empty($id)){
			//事务回滚
			$startTuarn && $model->rollback();
			if (!$error[1] || $error==1){
				return $id;
			}else {
                $this->handelResult($error,$url,1); //返回错误信息
			}
		}else {
			if (!$error[0] || $error==1){
				return $id;
			}else {
//                $this->add_log($model->getTableName()); //日志记录
                $startTuarn && $model->commit(); //事务提交
                $this->handelResult($error,$url,0); //返回错误信息
			}
		}
	}
	
	
	/**
	 * 修改数据
	 * Enter description here ...
	 * @param unknown_type $model 模型
	 * @param int|string $error 错误信息, 默认空返回结果 ， 为字符串时"成功时输出|失败时|请求方式"，按结果输出
	 * @param int|string $url 成功后跳转地址, 默认空 , 为字符串时 "[模块/][控制器/]操作|[模块/][控制器/]操作",按结果跳转
	 * @param unknown_type $condition 条件
	 * @param unknown_type $data 要修改的数据
	 * @param unknown_type $startTuarn 是否事务
	 */
	protected function editData($model='',$error='',$url='',$condition='',$data = '',$startTuarn = ''){
        //分解返回信息,$error[0]成功时返回,$error[1]失败时返回
        if(!is_numeric($error)){
            $error && $error = explode('|', $error);
        }

		//赋值模型
		$model = empty($model) ? $this->model : $model;
		
		//创建数据
		if (!$model->create($data,2)){
			$this->error($model->getError(),$url[1]);
		}

		//修改数据
        if(empty($condition)){
            $pk_id = I('pk_id');
            $pk_id && $condition['pk_id'] = $pk_id;
        }

        if(empty($condition)){
            $this->error('修改条件为空',$url[1]);
        }
		$id = $model->where($condition)->save();
		if ($id === false){
			//事务回滚
			$startTuarn && $model->rollback();

			if (!$error[1] || $error==1){
                //返回处理结果
				return $id;
			}else {
                //返回错误信息
                $this->handelResult($error,$url,1);
            }
		}else {
			if (!$error[0] || $error==1){
				return $id;
			}else {
                //日志记录
//                $this->add_log($model->getTableName());

				//事务提交
				$startTuarn && $model->commit();
                $this->handelResult($error,$url,0);
			}
		}
	}

    /**
     * 处理结果并返回
     * @param $error 0成功 1失败
     * @param $url
     */
    protected function handelResult($error,$url,$errorNo=0){
        //分解处理后跳转地址 $url[0]成功时,$url[1]失败时
        $url && $url = explode('|', $url);
        if ($error[$errorNo+1] || (IS_AJAX && MODULE_NAME != 'System')) {
            //停止运行,json返回
            if($url[$errorNo]) $this->data['url'] = $url[$errorNo];
            $this->rtnResult($errorNo, $error[$errorNo]);
        } else {
            //停止运行,tp内置返回
            if($errorNo == 0){
                $this->success($error[$errorNo], $url[$errorNo]);
            }else{
                $this->error($error[$errorNo], $url[$errorNo]);
            }
        }
    }

    /**
     * 事务结果返回
     * Enter description here ...
     * @param unknown_type $model 模型
     * @param unknown_type $mark 标记，有值则出错
     * @param unknown_type $error 错误码
     * @param unknown_type $url 跳转地址
     */
    function transReturn($model,$mark,$error,$url=''){
        $error && $error = explode('|', $error);
        if ($mark){
            $model->rollback();
            $this->handelResult($error,$url,1);
        }else {
            $model->commit();
            $this->handelResult($error,$url,0);
        }
    }

    /**
     * 删除数据(支持批删)
     * @param $model 模型
     * @param string $error 错误信息, 默认空返回结果 ， 为字符串时"成功时输出|失败时"，按结果输出
     * @param string $condition 条件,当等于数值时当成ID处理
     * @param string $url 成功后跳转地址, 默认空 , 为字符串时 "[模块/][控制器/]操作|[模块/][控制器/]操作",按结果跳转
     * @param string $startTuarn 是否事务
     * @return bool
     */
	protected function delData($model,$error='',$condition='',$url='',$startTuarn=''){
        //分解返回信息,$error[0]成功时返回,$error[1]失败时返回
        if(!is_numeric($error)){
            $error && $error = explode('|', $error);
        }

		//赋值模型
		$model = empty($model) ? $this->model : $model;
		
		//条件为空时自动获取要删除的对象
		if (empty($condition)){
			$pk_id = I('pk_id',I('id'));
			if ($pk_id){
                $condition['pk_id'] = is_array($pk_id) ? array('in',$pk_id) : $pk_id;
			}else {
				$this->error('不存在的数据对象');
			}
		}

		//开始删除
		if ($model->where($condition)->setField('status',1) === false){
			//事务回滚
			$startTuarn && $model->rollback();
			
			if (!$error[1] || $error==1){
				return true;
			}else {
                $this->handelResult($error,$url,1); //处理结果
			}
		}else {
			if ($error==1){
				return true;
			}else {
				if (!$error[0] || $error==1){
					return true;
				}else {
//                    $this->add_log($model->getTableName()); //日志记录
					$startTuarn && $model->commit(); //事务提交
                    $this->handelResult($error,$url,0); //处理结果
				}
			}
		}
	}
	
    /**
     * 新增数据
     */
    protected function add(){
        if (IS_AJAX){
            $this->addData($this->model,'添加成功|添加失败','index');
        }else {
            $this->showView('','edit');
        }
    }

    /**
     * 删除数据
     * POST请求为批删，GET请求为删除单条
     */
    protected function del(){
        $this->delData($this->model,'删除成功|删除失败|ajax');
    }

    protected function createApprovalNo(){
        return date('YmdHis').mt_rand(100,999);
    }
}

?>